package com.example.dayday.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.dayday.common.R;
import com.example.dayday.pojo.Student;
import com.example.dayday.pojo.Teacher;
import com.example.dayday.pojo.User;
import com.example.dayday.service.StudentService;
import com.example.dayday.vo.StudentVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.stream.Stream;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Helen
 * @since 2022-09-07
 */
@RestController
@RequestMapping("/student")
@Api(tags = "学生")
public class StudentController {

    @Autowired
    private StudentService studentService;



    @ApiOperation(value = "学生分页")
    @GetMapping("/findStudent")
    public R findStudent(int page, int limit, String studentName, Long studentId){
     IPage studentVoPage=   studentService.selectStudent(page,limit,studentName,studentId);
        return R.ok().data("iPage",studentVoPage);
    }

    @ApiOperation(value = "添加新的学生信息")
    @PostMapping("/addStudent")
   public R addStudent(@RequestBody Student student,HttpSession session){
        //要管理员才能添加
        User user = (User) session.getAttribute("user");
        if(user.getRole()==2){
            Teacher teacher = (Teacher) user;
            if("1".equals(teacher.getIsAdmin())){//如果是管理员
                student.setPassword("123456");
                //查询最大学号，最好写sql语句
                LambdaQueryWrapper<Student> wrapper = new LambdaQueryWrapper<>();
                wrapper.orderByDesc(Student::getStudentId).last("limit 1");
                Student one = studentService.getOne(wrapper);

                Long studentId = one.getStudentId();//数据库最大学号  20190001

                LocalDateTime now = LocalDateTime.now();
                int year = now.getYear(); //今年 2022

                if(year * 10000-studentId<0){ //表示最大的已经是超过今年，今年已经有学生
                    student.setStudentId(one.getStudentId()+1);
                }else{ //今年还没有学生
                    student.setStudentId((long) (year * 10000  + 1));
                }
                studentService.save(student);
                return R.ok().message("成功");
            }
        }
        return R.error("没有权限");

   }

    @ApiOperation(value = "删除一个学生信息")
   @DeleteMapping("/delectStudent")
    public R  delectStudent(Long id){
        studentService.removeById(id);
        return  R.ok().message("成功");
   }

   @ApiOperation(value = "修改学生信息")
    @PutMapping("/updateStudent")
   public R updateStudent(@RequestBody Student student,HttpSession session){

       //是否是管理员来修改
       User user = (User) session.getAttribute("user");
       if(user.getRole()==2){
           Teacher teacher = (Teacher) user;
           String isAdmin = teacher.getIsAdmin();
           if(!"1".equals(isAdmin)){
              //普通老师无权修改
               return R.error("无权修改");
           }
       }else{ //学生身份
           Student s = (Student) user;
           if(!s.getStudentId().equals(student.getStudentId())){ //表示登录的人和修改的人不是一个人
               return R.error("无权修改");
           }
       }

       //修改
       boolean b = studentService.updateById(student);
       if(b){
           if(user.getRole()==1){//如果当前登录的是自己，session中的数据更新
               Student s = (Student) user;
               if(student.getStudentId().equals(s.getStudentId())){
                   student.setRole(1);
                   student.setUserId(student.getStudentId());
                   session.setAttribute("user",student);
               }
           }
           return  R.ok().message("成功");
       }
       return  R.error("失败");

   }
    @ApiOperation(value = "根据id查询学生信息")
    @GetMapping("/getStudent")
   public R getStudent(Long id){
       Student student = studentService.getById(id);
       student.setRole(1);
        return  R.ok().data("user",student);
   }

    @ApiOperation(value = "修改学生密码")
    @PostMapping("/updatePassword")
    public R updatePassword(String studentId,String oldPassword, String newPassword, String twoPassword, HttpSession session){
        if(StringUtils.isEmpty(newPassword)){
            return R.error("新密码未输入");
        }
        if(StringUtils.isEmpty(twoPassword)){
            return R.error("确认密码未输入");
        }
        if(!newPassword.equals(twoPassword)){
            return R.error("两次密码不一致");
        }

        //是否是管理员来修改
        User user = (User) session.getAttribute("user");
        if(user.getRole()==2){
            Teacher teacher = (Teacher) user;
            String isAdmin = teacher.getIsAdmin();
            if("1".equals(isAdmin)){
                if(StringUtils.isEmpty(studentId)){
                    return R.error("学生id未输入");
                }
                boolean b = studentService.updatePassword(newPassword, Long.valueOf(studentId));
                if (b){
                    return  R.ok().message("修改成功");
                }
                return R.error("该学生id不存在");
            }else{
                return R.error("无权修改");
            }
        }

        //如果是学生自己来修改
        if(StringUtils.isEmpty(studentId)){
            return R.error("学生id未输入");
        }
        Student student = (Student) user;

        if(!student.getStudentId().equals(Long.valueOf(studentId))){//如果不是当前自己
            return R.error("无权操作");
        }

        if(StringUtils.isEmpty(oldPassword)){
            return R.error("旧密码未输入");
        }

        boolean b = studentService.updatePassword(oldPassword, newPassword, student.getStudentId());
        if (b){
            return  R.ok().message("修改成功");
        }
        return R.error("修改失败,旧密码错误");
    }
    @ApiOperation(value = "导入")
    @PostMapping("importData")
    public void importData(MultipartFile file,
                        HttpServletResponse response,
                        HttpServletRequest request) {
        try {
            studentService.importData(file);
            response.sendRedirect(request.getContextPath()+"/dayday/tab-panel.html?upload=true");
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

